package com.jyw.business.obstacles.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jyw.business.obstacles.constant.TalkTypeConstant;
import com.jyw.business.obstacles.domain.ObsPhoneBox;
import com.jyw.business.obstacles.domain.dto.web.VAAEventDto;
import com.jyw.business.obstacles.domain.vo.web.VAARedisVO;
import com.jyw.business.obstacles.service.IObsPhoneBoxService;
import com.jyw.business.obstacles.utils.PhoneUtils;
import com.jyw.business.obstacles.utils.ProcessUtils;
import com.jyw.common.annotation.Anonymous;
import com.jyw.common.core.redis.RedisCache;
import com.jyw.common.exception.ServiceException;
import com.jyw.common.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * @author 沈峻
 * @ClassName VAAPhoneBoxController
 * @Description 先锋音讯接口
 * @Date 2023/7/7 16:57
 **/
@RestController
@RequestMapping("vaa")
@Api(tags = "影音先锋")
@Slf4j
public class VAAPhoneBoxController {

    @Resource
    private RedisCache redisCache;

    @Resource
    private IObsPhoneBoxService phoneBoxService;

    @Resource
    private PhoneUtils phoneUtils;

    @Resource
    private ProcessUtils processUtils;

    /**
     * 盒子接收事件
     */
    @PostMapping("event")
    @ApiOperation("盒子事件请求")
    @Anonymous
    public String evnet(VAAEventDto dto, HttpServletRequest request){
        log.info("vaa进入了 POST");
        JSONObject json = new JSONObject();
        while (request.getParameterNames().hasMoreElements()) {
            String parm = request.getParameterNames().nextElement();
            json.put(parm,request.getParameter(parm));
        }
        log.info("@先锋音讯:参数值:{}",json);


        log.info("@先锋音讯:收到通道{}的消息:({})",dto.getLine(), JSONObject.toJSONString(dto));
        //处理业务数据
        processData(dto);

        return "0000";
    }

    @PostMapping("upload")
    @ApiOperation("vaa录音文件上传")
    @Anonymous
    public String evnet(MultipartRequest request){
        MultipartFile files = request.getFile("files");

        try {
            String url = processUtils.uploadVaa(files);
            phoneBoxService.saveVaaFile(files,url);
        } catch (IOException e) {
            log.error("文件上传异常",e);
            throw new ServiceException("上传录音文件异常");
        } catch (InterruptedException e) {
            log.error("文件上传异常,线程休眠问题",e);
            throw new ServiceException("上传录音文件异常");
        }


        return "0000";
    }

    /**
     * 数据处理
     * @param dto
     */
    private void processData(VAAEventDto dto){
        String redisKey = "VAA:"+dto.getCallid();
        switch (dto.getEvent_type()){
            case 3:
                log.info("@先锋音讯:收到通道{}的状态提机",dto.getLine());
                break;
            case 4:
                log.info("@先锋音讯:收到通道{}的提机",dto.getLine());
                break;
            case 5:
                log.info("@先锋音讯:收到通道{}的来电",dto.getLine());
                if(!StringUtils.isEmpty(dto.getCaller())&&!redisCache.hasKey(redisKey)){
                    dto.setCaller(phoneUtils.filterIncomingPrefix(dto.getCaller()));

                    redisCache.setCacheObject(redisKey, VAARedisVO.buildCallIn(dto));
                    //创建未接数据
                    phoneBoxService.startWork(dto.getCaller(),dto.getCallid(),dto.getPortName(), dto.getDate());
                }
                break;
            case 7:
                log.info("@先锋音讯:收到通道{},当前来电接听中",dto.getLine());
                if(redisCache.hasKey(redisKey)){
                    VAARedisVO vaaRedisDto = redisCache.getCacheObject(redisKey);
                    if(vaaRedisDto.getType().equals(TalkTypeConstant.MISSED_CALL)){
                        ObsPhoneBox externalPhoneBox = phoneBoxService.getByOtheraccept(dto.getCallid());
                        if(externalPhoneBox != null) {
                            //接通号码
                            externalPhoneBox.setOtherStr(dto.getPortName());
                            //已接
                            externalPhoneBox.setStatus("1");
                            externalPhoneBox.setAnsweredTime(new Date());
                            phoneBoxService.save(externalPhoneBox);
                        }
                        vaaRedisDto.setType(TalkTypeConstant.PICKED_UP);
                        redisCache.setCacheObject(redisKey,JSON.toJSONString(vaaRedisDto));
                    }
                }else{
                    if(!StringUtils.isEmpty(dto.getCaller())){
                        dto.setCaller(phoneUtils.filterIncomingPrefix(dto.getCaller()));
                        redisCache.setCacheObject(redisKey, JSON.toJSONString(VAARedisVO.buildCallIn(dto)));
                        //创建未接数据
                        phoneBoxService.startWork(dto.getCaller(),dto.getCallid(),dto.getPortName(), dto.getDate());
                        processData(dto);
                    }
                }
                break;
            case 8:
                log.info("@先锋音讯:收到通道{}当前状态为挂机",dto.getLine());
                break;
            case 9:
                log.info("@先锋音讯:收到通道{},当前状态为去电录音生成",dto.getLine());
                if(!redisCache.hasKey(redisKey)){
                    redisCache.setCacheObject(redisKey,JSONObject.toJSONString(VAARedisVO.buildCallOut(dto)));
                }
            case 10:
                //接收到当前事件,就可以判断为用户挂机
                log.info("@先锋音讯:收到通道{}当前状态为来电录音生成",dto.getLine());
                if(redisCache.hasKey(redisKey)){
                    ObsPhoneBox externalPhoneBox = phoneBoxService.getByOtheraccept(dto.getCallid());
                    if(externalPhoneBox != null) {
                        //用于挂机后拉取录音数据的序列号
                        externalPhoneBox.setCallAccept(dto.getFilePath());
                        externalPhoneBox.setOverTime(DateUtils.getNowDate());
                        phoneBoxService.save(externalPhoneBox);
                    }
                    VAARedisVO vaaRedisDto = redisCache.getCacheObject(redisKey);
                    vaaRedisDto.setFilePath(dto.getFilePath());
                    redisCache.setCacheObject(redisKey, JSON.toJSONString(vaaRedisDto));

                }else{
                    log.error("@先锋音讯,来电录音,丢失来电信息",dto);
                }
                break;
        }
    }



}
